// Book 类
case class Book(title: String, author: String, isbn: String) {
  private var isBorrowed: Boolean = false

  def borrow(): Boolean = {
    if (!isBorrowed) {
      isBorrowed = true
      true
    } else {
      false
    }
  }

  def returnBook(): Unit = {
    isBorrowed = false
  }
}

object Book {
  def apply(title: String, author: String, isbn: String): Book = new Book(title, author, isbn)

  def unapply(book: Book): Option[(String, String, String)] = Some((book.title, book.author, book.isbn))
}

// Library 类
class Library {
  private var availableBooks: List[Book] = List()
  private var borrowedBooks: List[Book] = List()

  def addBook(book: Book): Unit = {
    availableBooks = book :: availableBooks
  }

  def borrowBook(isbn: String): Option[Book] = {// 伴生对象，使用 apply/unapply
    availableBooks.find(_.isbn == isbn) match {
      case Some(book) =>
        if (book.borrow()) {
          availableBooks = availableBooks.filterNot(_.isbn == isbn)
          borrowedBooks = book :: borrowedBooks
          Some(book)
        } else {
          None
        }
      case None => None
    }
  }

  def returnBook(isbn: String): Boolean = {
    borrowedBooks.find(_.isbn == isbn) match {
      case Some(book) =>
        book.returnBook()
        borrowedBooks = borrowedBooks.filterNot(_.isbn == isbn)
        availableBooks = book :: availableBooks
        true
      case None => false
    }
  }
}

// 测试
object LibraryTest extends App {
  val library = new Library
  val book1 = Book("Scala Programming", "Martin Odersky", "123456")
  val book2 = Book("Functional Programming", "Paul Chiusano", "654321")

  library.addBook(book1)
  library.addBook(book2)

  println(library.borrowBook("123456")) // Some(Book)
  println(library.returnBook("123456")) // true
}
